import { Message } from '@/tool/antdv';
import axios from 'axios'
import { GetToken,SetToken,GetSelectedKeys } from './common';
import { iError } from '@/protobuf/interface/index'
import { OpenPage } from './utils';

const env = import.meta.env

const service = axios.create({
    baseURL: env.VITE_APP_DEV,
    timeout: 15000,
    headers: {"Content-Type": "application/json;charset=UTF-8"},
    withCredentials: true,
})


service.interceptors.request.use(function (config) {
    var token = GetToken()
    if (token) config.headers.Authorization = token;
    return config;
}, function (error) {
    return Promise.reject(error);
});

service.interceptors.response.use(function (response) {
    if(response.status === 200 && response.data.code == 0) {
        let rToken = response.headers['refresh-token'] || ""
        if (rToken !== "") {
            SetToken(rToken)
        }
        const result = response.data.data
        return result;
    }
    switch (response.data.code) {
        case iError.AuthTokenExpire:
            SetToken("")
            var selectedKeys = GetSelectedKeys()
            var data: any = {}
            if(selectedKeys && selectedKeys.length > 0) {
                data["redirect"] = "/" + selectedKeys[0]
            }
            OpenPage({url: "/login", data: data})
            break;
        default:
    }
    Message.error({
        content: response.data.message,
    });
    return Promise.reject(response);
}, function (error) {
    var message = error.code
    Message.error({
        content: message,
    });
    return Promise.reject(error);
});

export default service